package cn.tedu.smartos.health.service.impl;

import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.health.mapper.HealthMapper;
import cn.tedu.smartos.health.pojo.dto.HealthAddParam;
import cn.tedu.smartos.health.pojo.entity.HealthData;
import cn.tedu.smartos.health.pojo.vo.HealthDataVO;
import cn.tedu.smartos.health.service.HealthService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.github.pigmesh.ai.deepseek.core.DeepSeekClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.tedu.smartos.health.service.HealthAlertDetectionService;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class HealthServiceImpl implements HealthService {
    @Autowired
    private HealthMapper healthMapper;
//    @Autowired
//    private DeepSeekClient deepSeekClient;
    @Autowired
    private HealthAlertDetectionService healthAlertDetectionService;
    /**
     * 添加数据
     * @param healthAddParam
     */
    @Override
    public void add(HealthAddParam healthAddParam) {
        log.debug("开始处理【添加健康数据】的请求，参数：{}", healthAddParam);
        // 创建HealthData对象
        HealthData healthData = new HealthData();
        BeanUtils.copyProperties(healthAddParam, healthData);
//        healthData.setUploadTime(new Date());
        healthData.setUploadTime(new Date());
// 设置是否正常
        boolean isNormal = healthAlertDetectionService.isDataNormal(healthData);
        healthData.setIsNormal(isNormal ? 1 : 0);
        // 手动设置 elderly_user_id，防止为 null
        if (healthAddParam.getElderlyUserId() != null) {
            healthData.setElderlyUserId(healthAddParam.getElderlyUserId());
        } else {
            throw new IllegalArgumentException("老人用户ID不能为空");
        }
        // 调用Mapper执行插入
        Integer rows = healthMapper.insertHealthData(healthData);
        if (rows != 1) {
            throw new ServiceException("健康数据插入失败");
        }

        healthAlertDetectionService.detectAndCreateAlert(healthData);
    }
    /**
     * 查询数据列表
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return PageInfo<HealthDataVO>
     */
    @Override
    public PageInfo<HealthDataVO> list(Integer pageNum, Integer pageSize, Long elderlyUserId){
        PageHelper.startPage(pageNum, pageSize);
        List<HealthDataVO> data = healthMapper.listHealth(elderlyUserId);
        return new PageInfo<>(data);
    }
}
